extends Node

var set_dic: Dictionary = {}

signal is_load_over

func _init() -> void :
	GameEvents.set_end.connect(save_set)




func save_set() -> void :
	set_dic = Global.current_setting
	var file = FileAccess.open("user://saveset.data", FileAccess.WRITE)
	file.store_var(set_dic)
	file.close()

func save_game():
	#MusicPlayer.play_sfx("Save")
	var file_path = "user://savegame.tres"
	var dir = DirAccess.open("user://")
	if dir.file_exists(file_path):
		dir.remove(file_path)
		print("已删除")
	var saved_game: SaveGame = SaveGame.new()

	saved_game.current_stage_name = Global.current_stage_name
	saved_game.current_star = DialogHandler.star

	var saved_data: Array[SavedData] = []
	get_tree().call_group("Can_Save", "on_save_game", saved_data)
	saved_game.saved_data = saved_data

	ResourceSaver.save(saved_game, "user://savegame.tres")
	print("已存档")



func load_set() -> void :
	var file = FileAccess.open("user://saveset.data", FileAccess.READ)
	if file != null:
		Global.current_setting = file.get_var()
	else:
		Global.current_setting = {
			"BGM": 0.5, 
			"SFX": 0.5, 
			"SIZE": Vector2(1280,720),
			"MODE": 1,
			"UNLOCK": false,
		}

func load_stage() -> void:
	var saved_game: SaveGame = load("user://savegame.tres")
	for save_data:SavedData in saved_game.saved_data:
		if save_data.current_count != 0 && save_data.id == DialogHandler.current_stage.current_npc.npc_id:
			DialogHandler.current_stage.current_npc.on_load_game(save_data)
		elif save_data.max_energy != 0:
			Global.player.on_load_game(save_data)


func load_game() -> bool :
	var saved_game: SaveGame = load("user://savegame.tres")
	if saved_game != null:
		Global.current_stage_name = saved_game.current_stage_name
		DialogHandler.star = saved_game.current_star
		await GameEvents.stage_entered
		for save_data:SavedData in saved_game.saved_data:
			if save_data.current_count != 0 && save_data.id == DialogHandler.current_stage.current_npc.npc_id:
				DialogHandler.current_stage.current_npc.on_load_game(save_data)
			elif save_data.max_energy != 0:
				Global.player.on_load_game(save_data)
		return true
	else:
		return false
